<template>
  <a-badge
    :count="count"
    :showZero="true"
    :number-style="{
      backgroundColor: bgColor,
      padding: '0',
      'font-size': '0.1rem',
    }"
    v-show="type !== 'star'"
  >
    <li
      class="item br-5 fx-c bg-w cs"
      :style="{ color: bgColor }"
      @click="addAgree(articleId)"
    >
      <a-icon :type="type" theme="filled" />
    </li>
  </a-badge>
</template>

<script>
import { mapState } from "vuex";
import { addAgree, get_one, getArticleDetail } from "@/api/article";
import { normlizeArticleMsg } from "@/utils/utils";
export default {
  name: "SideItem",
  props: {
    type: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      articleId: "",
      defaultAgree: false,
      count: 0,
      bgColor: "#b2bac2",
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  async created() {
    const type = this.type;
    this.articleId = this.$route.params.id;
    const { data } = await get_one(this.articleId);
    const { agreeUsers, comments } = data;
    if (type === "like") {
      this.count = agreeUsers.length;
      //   验证当前用户是否点赞过该文章
      this.defaultAgree = !!data.agreeUsers.find(
        (item) => item.id === this.user._id
      );
      if (this.defaultAgree) {
        this.bgColor = "#2AB765";
      }
    } else if (type === 'message'){
      this.count = comments.length;
      this.bgColor = this.count ? "#2AB765" : "#b2bac2"
    }
  },
  methods: {
    async addAgree(id) {
      if (this.type === "like") {
        if (!this.defaultAgree) {
          // 点赞
          const r = await addAgree(id, 1, this.user._id);
          if (r.code == 1) {
            this.defaultAgree = true;
            this.count = r.agree;
            this.bgColor = "#2AB765";
            this.$message.success(r.msg);
          } else {
            this.$message.error(r.msg);
          }
        } else {
          // 取消点赞
          const r = await addAgree(id, -1, this.user._id);
          if (r.code == 1) {
            this.defaultAgree = false;
            this.count = r.agree;
            this.bgColor = "#b2bac2";
            this.$message.success(r.msg);
          } else {
            this.$message.error(r.msg);
          }
        }
      } else if (this.type === "message") {
        window.scrollTo(0, 2400);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.item {
  width: 4rem;
  height: 4rem;
  margin-bottom: 1rem;
  color: #b2bac2;
}
</style>